package com.np.permission.demo1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import com.np.permission.demo1.utils.PermissionX;

public class SecondActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final int REQUEST_CODE_SMS = 1;
    private static final String[] PERMISSIONS_SMS = new String[]{
            android.Manifest.permission.SEND_SMS,
            android.Manifest.permission.READ_SMS
    };

    private static final int REQUEST_CODE_CONTACTS = 2;
    private static final String[] PERMISSIONS_CONTACTS = new String[]{
            android.Manifest.permission.READ_CONTACTS,
            android.Manifest.permission.WRITE_CONTACTS
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        // 第一种情况：打开主界面就需要用户授权
        PermissionX.checkPermission(this, PERMISSIONS_SMS, REQUEST_CODE_SMS);

        // 第二种情况：使用某个功能的时候才需要用户授权
        findViewById(R.id.btn_contact).setOnClickListener(v -> {
            PermissionX.checkPermission(this, PERMISSIONS_CONTACTS, REQUEST_CODE_CONTACTS);
        });
    }

    // 原生的回调：用户进行授权操作后的回调，可以根据授权结果进行后续的操作
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        boolean isAllGranted = true;    // 请求的权限是否全部被授权
        if (requestCode == REQUEST_CODE_SMS) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i(TAG, permissions[i] + " " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "已授权" : "未授权"));
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                }
            }
        }

        if (isAllGranted) {
            // 权限被授予，可以执行相应的操作
        } else {
            // 权限被用户拒绝，引导用户去设置页面手动开启
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", getPackageName(), null);
            intent.setData(uri);
            startActivity(intent);
        }
    }
}